<?php

	/**
	 * @package		CoreProject
	 * @subpackage	Mime
	 *
	 * cpr_Mime_TextBody
	 *
	 */

	class cpr_Mime_TextBody
	{
		const TYPE_PLAIN = 1;
		const TYPE_HTML = 2;

		/**
		 * @var	array
		 */
		private $_plain = array();

		/**
		 * @var	array
		 */
		private $_html = array();

		/**
		 * @var	int
		 */
		private $_type = 0;

		/**
		 * @var	cpr_Mime_GlobalCharset
		 */
		private $_global_charset;

		/**
		 * @param	cpr_Mime_GlobalCharset	$_gc
		 * @param	cpr_Mime_MimePart		$_mime
		 * @return	cpr_Mime_TextBody
		 */
		public function cpr_Mime_TextBody(&$_gc, &$_mime)
		{
			$this->_global_charset =& $_gc;
			$this->_searchTextBody($_mime);
		}

		/**
		 * @return	string
		 */
		public function GetPlain()
		{
			return implode(CPR_CRLF.CPR_CRLF, $this->_plain);
		}

		/**
		 * @return	array
		 */
		public function GetPlainParts()
		{
			return $this->_plain;
		}

		/**
		 * @return	string
		 */
		public function GetHtml()
		{
			return implode(CPR_CRLF.CPR_CRLF, $this->_html);
		}

		/**
		 * @return	array
		 */
		public function GetHtmlParts()
		{
			return $this->_html;
		}

		/**
		 * @return	int
		 */
		public function GetType()
		{
			return $this->_type;
		}

		/**
		 * @param	cpr_Mime_MimePart	$mimePart
		 */
		private function _searchTextBody($mimePart)
		{
			$subParts =& $mimePart->GetSubParts();
			if (null === $subParts)
			{
				$_headers =& $mimePart->GetHeaders();
				if ($_headers && !$_headers->IsAttachmentHeader())
				{
					$contentTypeL = strtolower($_headers->GetContentType());
					$contentTypeCharset = $_headers->GetContentTypeCharset();

					if (strlen($contentTypeCharset) > 0)
					{
						$this->_global_charset->SetMailCharset($contentTypeCharset);
					}

					if (strpos($contentTypeL, CPR_MIME_TEXT_HTML) !== false)
					{
						$preStr = '/(<meta\s.*)(charset\s?=)([^"\'>\s]*)/i';
						$this->_html[] = trim(preg_replace($preStr, '$1$2'.$this->_global_charset->GetDbCharset(), $mimePart->GetDecodeTextBody()));
						$this->_type |= self::TYPE_HTML;
					}
					else
					{
						$this->_plain[] = trim($mimePart->GetDecodeTextBody());
						$this->_type |= self::TYPE_PLAIN;
					}
				}
			}
			else
			{
				for ($i = 0, $c = $subParts->Count(); $i < $c; $i++)
				{
					$subPart =& $subParts->Get($i);
					$this->_searchTextBody($subPart);
				}
			}
		}
	}
